package com.zz.qimo.sqlite;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.zz.qimo.Product;
import com.zz.qimo.User;

import java.util.ArrayList;
import java.util.List;

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "CampusMarket.db";
    private static final int DATABASE_VERSION = 1;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建商品表
        String createProductsTable = "CREATE TABLE Products (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "name TEXT," +
                "price REAL," +
                "description TEXT)";
        db.execSQL(createProductsTable);

        // 创建用户表
        String createUsersTable = "CREATE TABLE Users (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "username TEXT," +
                "password TEXT)";
        db.execSQL(createUsersTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 升级数据库操作（如果需要）
    }

    // 添加商品到数据库
    public long addProduct(Product product) {
        SQLiteDatabase db = getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("name", product.getName());
        values.put("price", product.getPrice());
        values.put("description", product.getDescription());

        long productId = db.insert("Products", null, values);

        db.close();
        return productId;
    }

    // 获取所有商品
    @SuppressLint("Range")
    public List<Product> getAllProducts() {
        List<Product> productList = new ArrayList<>();
        String selectQuery = "SELECT * FROM Products";

        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                Product product = new Product();
                product.setId(cursor.getInt(cursor.getColumnIndex("id")));
                product.setName(cursor.getString(cursor.getColumnIndex("name")));
                product.setPrice(cursor.getDouble(cursor.getColumnIndex("price")));
                product.setDescription(cursor.getString(cursor.getColumnIndex("description")));

                productList.add(product);
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return productList;
    }

    // 添加用户到数据库
    public long addUser(User user) {
        SQLiteDatabase db = getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("username", user.getUsername());
        values.put("password", user.getPassword());

        long userId = db.insert("Users", null, values);

        db.close();
        return userId;
    }

    // 验证用户
    public boolean isValidUser(String username, String password) {
        SQLiteDatabase db = getReadableDatabase();

        String[] projection = {"id"};
        String selection = "username = ? AND password = ?";
        String[] selectionArgs = {username, password};

        Cursor cursor = db.query("Users", projection, selection, selectionArgs, null, null, null);
        boolean isValid = cursor.getCount() > 0;

        cursor.close();
        db.close();
        return isValid;
    }

    // 更新用户密码
    public int updateUserPassword(String username, String newPassword) {
        SQLiteDatabase db = getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("password", newPassword);

        int rowsAffected = db.update("Users", values, "username = ?", new String[]{username});

        db.close();
        return rowsAffected;
    }


}
